import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormSelect, ProFormDigit, ProFormDateTimePicker, ProFormGroup, ModalForm } from '@ant-design/pro-components';
import { Button, Form, message, Input, Descriptions, Divider, InputNumber, Switch } from 'antd';
import { useRequest } from 'umi';
import { createOrder, updateOrder, updateOrderAmount, updateOrderDetail, updateTokenStatus } from '@/services/ant-design-pro/order'; // 假设你已经定义了这些服务

const OrderForm: React.FC = ({ initialValues, isEditMode, onClose, onSuccess, handleAudit }) => {
  
  const { run } = useRequest((values) => (isEditMode ? updateOrder(values) : createOrder(values)), {
    manual: true,
    onSuccess: () => {
      message.success(isEditMode ? '更新成功' : '创建成功');
      onClose();
      onSuccess();
    },
    onError: () => {
      message.error(isEditMode ? '更新失败' : '创建失败');
    },
  });

  const { run: runUpdateAmount } = useRequest(updateOrderAmount, {
    manual: true,
    onSuccess: () => {
     const num = form.getFieldValue('discount');
     console.log(num)
      if(num >= 8)
      {
        message.success('金额更新成功');
      }else{
        message.success('已进入审批流程');
      }
      onClose();
      onSuccess();
    },
    onError: () => {
      // message.error('金额更新失败');
    },
  });

  const { run: runUpdateDetail } = useRequest(updateOrderDetail, {
    manual: true,
    onSuccess: () => {
      message.success('产品详情更新成功');
      onClose();
      onSuccess();
    },
    onError: () => {
      message.error('产品详情更新失败');
    },
  });

  const [orderDetails, setOrderDetails] = useState(initialValues?.orderDetailList || []);

  const cheangeStatus = async (data, detail) => {
   const res =  await updateTokenStatus(data);
    const updatedDetails = orderDetails.map(d => 
      d.id === detail.id ? { ...d, activationStatus: data.status } : d
    );
    if(res.data === true){
      setOrderDetails(updatedDetails);
      message.success('操作成功');
    }else{
      message.error('激活失败');
    }
    
  };
  // 监听 initialValues 变化，更新 orderDetails
  useEffect(() => {
    if (initialValues?.orderDetailList) {
      setOrderDetails(initialValues.orderDetailList);
    }
  }, [initialValues?.orderDetailList]);
  const [form] = ProForm.useForm();
  const handleAmountChange = (value) => {
    console.log(value,initialValues.payAmount)
    const discount =   parseFloat((value / initialValues.orderAmount * 10).toFixed(1)); 
  
    form.setFieldsValue({ discount });
  };

  const handleDiscountChange = (value) => {
    const amount = initialValues.orderAmount * value / 10;
    form.setFieldsValue({ amount });
  };
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (visible) {
      // 重置表单字段
      form.resetFields();
    
    }
  }, [visible]);

  return (
    <>
      <Descriptions title="会员信息" bordered layout="vertical">
        <Descriptions.Item label="会员名称">{initialValues?.userName || '-'}</Descriptions.Item>
        <Descriptions.Item label="会员手机号">{initialValues?.mobile || '-'}</Descriptions.Item>
        <Descriptions.Item label="会员邮箱">{initialValues?.email || '-'}</Descriptions.Item>
        <Descriptions.Item label="注册时间">{initialValues?.registerTime || '-'}</Descriptions.Item>
        <Descriptions.Item label="地址">{initialValues?.companyAddress || '-'}</Descriptions.Item>
        <Descriptions.Item label="详细地址">{initialValues?.companyAddressDetail || '-'}</Descriptions.Item>
        <Descriptions.Item label="账户类型">{initialValues?.accountType || '-'}</Descriptions.Item>
        <Descriptions.Item label="公司名称">{initialValues?.companyName || '-'}</Descriptions.Item>
      </Descriptions>

      <Descriptions title="产品详情" style={{ marginTop: 24 }} layout="vertical">
      </Descriptions>
      {orderDetails.map((detail, index) => (
        <React.Fragment key={index}>
          <Descriptions title={detail.orderName} bordered style={{ marginTop: 24 }} layout="vertical">
            <Descriptions.Item label="服务编号">{detail.orderCode || '-'}</Descriptions.Item>
            <Descriptions.Item label="服务城市">{detail.serviceCity || '-'}</Descriptions.Item>
            <Descriptions.Item label="调用方式">{detail.callWay || '-'}</Descriptions.Item>
            <Descriptions.Item label="调用量">{detail.callCount || '-'}</Descriptions.Item>
            <Descriptions.Item label="天气类型">{detail.globalCity || detail.weatherType || '-'}</Descriptions.Item>
            <Descriptions.Item label="服务时长">{detail.serviceTime || '-'}</Descriptions.Item>
            <Descriptions.Item label="生效时间">{detail.effectTime || '-'}</Descriptions.Item>
            <Descriptions.Item label="使用状态">
              {detail.useStatus === 0 ? '待使用' : detail.useStatus === 1 ? '使用中' : detail.useStatus === 2 ? '已关闭' : detail.useStatus === 3 ? '待生效' : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="到期时间">{detail.expirationTime || '-'}</Descriptions.Item>
            <Descriptions.Item label="费用">{detail.amount || '-'}</Descriptions.Item>
            <Descriptions.Item label="accessId">
              {detail.spareInt2}
            </Descriptions.Item>
            <Descriptions.Item label="token">
              {detail.spareString1}
            </Descriptions.Item>
            <Descriptions.Item label="password">
              {detail.spareString2}
            </Descriptions.Item>
            <Descriptions.Item label="是否激活">
              <Switch checked={detail.activationStatus === 1} onChange={(checked) => cheangeStatus({ id: detail.id, status: checked ? 1 : 0 }, detail)} />
            </Descriptions.Item>
          </Descriptions>

          <ModalForm
            title="修改产品详情"
            initialValues={detail}
            trigger={<Button style={{ marginTop: 24 }} type="primary">修改产品详情</Button>}
            onFinish={async (values) => {
              await runUpdateDetail({ id: detail.id, ...values });
              return true;
            }}
          >
            <Form.Item
              name="spareInt2"
              label="accessId"
              rules={[{ required: true, message: '请输入accessId' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="spareString1"
              label="token"
              rules={[{ required: true, message: '请输入token' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="spareString2"
              label="password"
              rules={[{ required: true, message: '请输入password' }]}
            >
              <Input />
            </Form.Item>
          </ModalForm>
        </React.Fragment>
      ))}

      <Descriptions title="订单信息" bordered style={{ marginTop: 24 }} layout="vertical">
        <Descriptions.Item label="订单编码">{initialValues?.orderCode || '-'}</Descriptions.Item>
        <Descriptions.Item label="订单名称">{initialValues?.orderName || '-'}</Descriptions.Item>
        <Descriptions.Item label="订单金额"> ¥ {initialValues?.orderAmount || '-'}</Descriptions.Item>
        <Descriptions.Item label="订单状态">
          {initialValues?.orderStatus === 0 ? '待支付' :
            initialValues?.orderStatus === 1 ? '已完成' :
              initialValues?.orderStatus === 2 ? '已取消' :
                initialValues?.orderStatus === 3 ? '待退款' :
                  initialValues?.orderStatus === 4 ? '已退款' :
                    initialValues?.orderStatus === 5 ? '改价失败' :
                      initialValues?.orderStatus === 6 ? '订单超时失效' : '退款失败'}
        </Descriptions.Item>
        <Descriptions.Item label="支付方式">
          {initialValues?.payType === '0' ? '支付宝' :
            initialValues?.payType === '1' ? '微信' :
              initialValues?.payType === '2' ? '对公支付' :
                initialValues?.payType === '3' ? '免费' : '-'}
        </Descriptions.Item>
        <Descriptions.Item label="下单时间">{initialValues?.orderTime || '-'}</Descriptions.Item>
        <Descriptions.Item label="支付时间">{initialValues?.payTime || '-'}</Descriptions.Item>
        <Descriptions.Item label="支付单号">{initialValues?.payNo || '-'}</Descriptions.Item>
        <Descriptions.Item label="手机号">{initialValues?.mobile || '-'}</Descriptions.Item>
        <Descriptions.Item label="发票状态">
          {initialValues?.billStatus === 0 ? '未开' :
            initialValues?.billStatus === 1 ? '开票中' : '已开'}
        </Descriptions.Item>
      </Descriptions>

      <ModalForm
      form={form}
      open={visible}
        title="修改金额"
        trigger={initialValues?.orderStatus === 0 && initialValues?.payType !== '3' && <Button style={{ marginTop: 24 }} type="primary">修改金额</Button>}
        onFinish={async (values) => {
          await runUpdateAmount({ id: initialValues.id, ...values });
          return true;
        }}
      >
        <Form.Item
          name="amount"
          label="新金额"
          rules={[{ required: true, message: '请输入新金额' }]}
        >
          <InputNumber min={0} precision={2} style={{ width: '100%' }}   onChange={handleAmountChange}/>
        </Form.Item>
        <Form.Item
          name="discount"
          label="折扣"
          rules={[
            { 
              required: true,
              validator: async (_, value) => {
                if (value === undefined || value === null || value === '') {
                  throw new Error('请输入价格折扣');
                }
                if (value < 0 || value > 10) {
                  throw new Error('请输入0-10之间的数字，最多两位小数');
                }
                // 检查小数位数
                const decimalPlaces = value.toString().split('.')[1]?.length || 0;
                if (decimalPlaces > 2) {
                  throw new Error('最多支持两位小数');
                }
                return Promise.resolve();
              }
            }
          ]}
        >
          <InputNumber min={0}  precision={2} style={{ width: '100%' }}   onChange={handleDiscountChange}/>
        </Form.Item>
      </ModalForm>
    </>
  );
};

export default OrderForm;